using Microsoft.AspNetCore.Mvc;
using PandaWebAPI.Models.ef;
using PandaWebAPI.Services;

namespace PandaWebAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CommentController : ControllerBase
    {
        private readonly ICommentService _commentService;

        public CommentController(ICommentService commentService)
        {
            _commentService = commentService;
        }

        [HttpGet]
        public async Task<ActionResult<List<Comment>>> GetAllComments()
        {
            var comments = await _commentService.GetAllAsync();
            return Ok(comments);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Comment>> GetCommentById(Guid id)
        {
            var comment = await _commentService.GetByIdAsync(id);
            if (comment == null)
                return NotFound();

            return Ok(comment);
        }

        [HttpGet("post/{postId}")]
        public async Task<ActionResult<List<Comment>>> GetCommentsByPostId(Guid postId)
        {
            var comments = await _commentService.GetCommentsByPostIdAsync(postId);
            return Ok(comments);
        }

        [HttpGet("user/{userId}")]
        public async Task<ActionResult<List<Comment>>> GetCommentsByUserId(Guid userId)
        {
            var comments = await _commentService.GetCommentsByUserIdAsync(userId);
            return Ok(comments);
        }

        [HttpGet("{commentId}/replies")]
        public async Task<ActionResult<List<Comment>>> GetRepliesByCommentId(Guid commentId)
        {
            var replies = await _commentService.GetRepliesByCommentIdAsync(commentId);
            return Ok(replies);
        }

        [HttpPost]
        public async Task<ActionResult<Comment>> CreateComment(Comment comment)
        {
            var createdComment = await _commentService.CreateAsync(comment);
            return CreatedAtAction(nameof(GetCommentById), new { id = createdComment.CommentId }, createdComment);
        }

        [HttpPut("{id}")]
        public async Task<ActionResult<Comment>> UpdateComment(Guid id, Comment comment)
        {
            if (id != comment.CommentId)
                return BadRequest();

            try
            {
                var updatedComment = await _commentService.UpdateAsync(comment);
                return Ok(updatedComment);
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteComment(Guid id)
        {
            var result = await _commentService.DeleteAsync(id);
            if (!result)
                return NotFound();

            return NoContent();
        }
    }
} 